package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;


public class ZhongChenYuanServiceImpl {
	private static Logger logger = Logger.getLogger(ZhongChenYuanServiceImpl.class);
	public static ZhongChenYuanServiceImpl service = new ZhongChenYuanServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.ZHONGCHENYUAN_ORDER_URL;
	private static String ZHONGCHENYUAN_INTERFACESIGN = BetweenProperties.ZHONGCHENYUAN_INTERFACESIGN;
	private static String ZHONGCHENYUAN_USERNAME = BetweenProperties.ZHONGCHENYUAN_USERNAME;
	private static String ZHONGCHENYUAN_PASSWORD = BetweenProperties.ZHONGCHENYUAN_PASSWORD;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.ZHONGCHENYUAN_ORDERSTATUS_URL;
	
	

	public String order(String proKey, String mobile, String orderNo,String bcallbackUrl,String productId) {
		logger.info("between- 中琛源订单ZhongChenYuanServiceImpl.order() 订购请求params<>: proKey = " + proKey
				+ ", mobile = " + mobile + ", orderNo = " + orderNo+ ", bcallbackUrl = " + bcallbackUrl+",productId="+productId);
        String userName = ZHONGCHENYUAN_USERNAME;
        String userPwd = ZHONGCHENYUAN_PASSWORD;
        String interfaceSign = ZHONGCHENYUAN_INTERFACESIGN;
        String businessType = "2";
       
        String sign = getMD5("userName="+userName+"&userPwd="+getMD5(userPwd)+ interfaceSign +"&mobile="+mobile+"&proKey="+proKey+"&orderNo="+orderNo+"&bcallbackUrl="+bcallbackUrl);
        String result = "";
        
        String flowType = "";//默认为空
        //LTALY300030，LTALY300300，LTALY301024
        if ("LTALY300030".equals(productId)||"LTALY300300".equals(productId)||"LTALY301024".equals(productId)) {
			flowType="RF";
		}else if (productId.startsWith("LTAL")||productId.startsWith("DXAL")||productId.startsWith("YDAL")) {
			flowType ="AF";
		}else if(productId.startsWith("LT")||productId.startsWith("DX")||productId.startsWith("YD")){
			flowType ="SF";
		}
	
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("orderNo",orderNo));//订单号
        pairList.add(new BasicNameValuePair("mobile",mobile));//充值手机号
        pairList.add(new BasicNameValuePair("userName",userName));//公司管理员账号admin@2000703175
        pairList.add(new BasicNameValuePair("userPwd",getMD5(userPwd)));//公司管理员密码
        pairList.add(new BasicNameValuePair("proKey",proKey));//充值的流量套餐编码
        pairList.add(new BasicNameValuePair("bcallbackUrl",bcallbackUrl));//充值成功回调地址
        pairList.add(new BasicNameValuePair("flowType",flowType));// AF全网  SF 省网   RF红包
        pairList.add(new BasicNameValuePair("sign",sign));//签名认证
        pairList.add(new BasicNameValuePair("businessType",businessType));//1话费  2流量
        pairList.add(new BasicNameValuePair("f","recharge"));// 方法
       
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 中琛源流量订购请求时的参数: " + pairList);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 中琛源流量订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 中琛源流量订购请求时的响应数据是: " + result);
			}
			
		} catch (Exception e) {
			logger.info("between- 中琛源流量订购请求异常: " + e.getMessage());
		}
		return result;
	}

	
	
	
	
	
	
	public String orderStatus(String cstmOrderNo) {

		logger.info("between- 中琛源订购状态请求参数: params cstmOrderNo = " + cstmOrderNo);
		String userName = ZHONGCHENYUAN_USERNAME;
	    String userPwd = ZHONGCHENYUAN_PASSWORD;
	    String interfaceSign = ZHONGCHENYUAN_INTERFACESIGN;
	    String sign = getMD5("userName="+userName+"&userPwd="+getMD5(userPwd)+ interfaceSign +"&orderNo="+cstmOrderNo);//md5加密
	    String businessType = "2";
	    String result = "";
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("orderNo",cstmOrderNo));
        pairList.add(new BasicNameValuePair("userName",userName));
        pairList.add(new BasicNameValuePair("userPwd",getMD5(userPwd)));
        pairList.add(new BasicNameValuePair("sign", sign));
        pairList.add(new BasicNameValuePair("f","resultQuery"));
        pairList.add(new BasicNameValuePair("businessType",businessType));
        
    	HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 中琛源流量订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 中琛源流量订购请求时的响应数据是: " + result);
			}
		} catch (Exception e) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", "100");
			map.put("tip", e.getMessage());
			result = new Gson().toJson(map);
		}
		return result;
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}

	public static void main(String[] args) {
		String productId = "LTALY300300";
		    String flowType = "";//默认为空
	        //LTALY300030，LTALY300300，LTALY301024
	        if ("LTALY300030".equals(productId)||"LTALY300300".equals(productId)||"LTALY301024".equals(productId)) {
				flowType="RF";
			}else if (productId.startsWith("LTAL")||productId.startsWith("DXAL")||productId.startsWith("YDAL")) {
				flowType ="AF";
			}else if(productId.startsWith("LT")||productId.startsWith("DX")||productId.startsWith("YD")){
				flowType ="SF";
			}
	        System.out.println(flowType);
	}

}
